package fieldmaps.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import fieldmaps.exceptions.DatabaseException;

public class DatabaseConnection {
	
	private static String driver = "org.postgresql.Driver";
	private static String connectString = "jdbc:postgresql://localhost:5432/field_maps";
	private static String user = "postgres";
	private static String password = "1234";
	
	private static Connection databaseConnection;
	
	private static Logger LOGGER = Logger.getLogger(DatabaseConnection.class);
	
	private DatabaseConnection () {
		
	}
	
	public static Connection getConnectionInstance () {
		try {
			if (databaseConnection == null) {
				Class.forName(driver);
				databaseConnection = DriverManager.getConnection(connectString, user, password);
				LOGGER.info("DataBase connection successfully done!");
			}
			return databaseConnection;
		} catch (SQLException e) {
			LOGGER.error(e.getMessage());
		} catch (ClassNotFoundException e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}
	
	public static void setConnectionParameters (String driver, String connectString, String user, String password) throws DatabaseException {
		if (DatabaseConnection.databaseConnection == null) {
			DatabaseConnection.driver = driver;
			DatabaseConnection.connectString = connectString;
			DatabaseConnection.user = user;
			DatabaseConnection.password = password;
		} else {
			throw new DatabaseException("There is an active connection. You must reset that before starting another!");
		}
	}
	
	public static void resetConnectionInstance () {
		databaseConnection = null;
	}
}
